package com.w1.security.handler.authHandler;

import com.alibaba.fastjson.JSON;
import com.w1.security.Mapper.UserMapper;
import com.w1.security.domain.LoginUser;
import com.w1.security.domain.ResponseResult;
import com.w1.security.service.IUserService;
import com.w1.security.utiles.JwtUtil;
import com.w1.security.utiles.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * 认证成功处理器
 * @author mingyifan
 * @date 2022-02-24 16:17
 */
@Component
public class AuthSuccessHandler implements AuthenticationSuccessHandler {
    @Autowired
    private UserMapper userMapper;
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication auth) throws IOException, ServletException {
        System.out.println("认证成功");
        LoginUser loginUser = (LoginUser) auth.getPrincipal();
        String jwt = JwtUtil.createJWT(JSON.toJSONString(loginUser.getUser()));
        //写cookie
        Cookie cookie = new Cookie("Authorization", jwt);
        cookie.setPath("/");
        cookie.setMaxAge(60*60*24);
        response.addCookie(cookie);
        //更新最后一次登陆地址
        HashMap<String, Object> map = new HashMap<>();
        map.put("ip",httpServletRequest.getRemoteAddr());
        map.put("id",loginUser.getUser().getId());
        int i = userMapper.updateLoginIp(map);
        if (i==1){
            ResponseResult responseResult = new ResponseResult(HttpStatus.OK.value(),"登陆成功");
            WebUtils.renderString(response, JSON.toJSONString(responseResult));
        }

    }
}
